package cn.yx.common.security.service;

import cn.yx.common.core.enums.RandomCodeEnum;
import cn.yx.common.core.util.RandomUtil;
import cn.yx.common.redis.service.RedisService;
import cn.yx.common.security.constants.SecurityRedisCacheConstant;
import cn.yx.common.security.properties.SecurityProperties;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * <p>SecurityCodeService验证码服务类</p>
 *
 * @author Wgssmart
 */
@Component
public class SecurityCodeService {

    private final RedisService redisService;

    private final SecurityProperties securityProperties;

    public SecurityCodeService(SecurityProperties securityProperties, RedisService redisService) {
        this.redisService = redisService;
        this.securityProperties = securityProperties;
    }

    /**
     * 获取手机登录验证码
     *
     * @param phone
     */
    public String loginSmsCode(String phone) {
        String key = SecurityRedisCacheConstant.SMS_CODE_LOGIN_PREFIX + phone;
        if (redisService.hasKey(key)) {
            // 如果验证码未过期，则直接返回未过期的验证码
            return (String) redisService.get(key);
        }
        // 验证码不存在，则生成验证码并缓存
        String smsCode = RandomUtil.randomCode(RandomCodeEnum.NUMBER_CODE, securityProperties.getSmsCode().getSmsCodeLength());
        redisService.set(key, smsCode,
                securityProperties.getSmsCode().getSmsCodeExpiration(), TimeUnit.MINUTES);
        return smsCode;
    }

    /**
     * 获取普通登录验证码
     *
     * @param sessionId
     */
    public String loginVerifyCode(String sessionId) {
        String verifyCode = RandomUtil.randomCode(RandomCodeEnum.MIX_CODE, securityProperties.getVerifyCode().getVerifyCodeLength());
        redisService.set(SecurityRedisCacheConstant.CODE_LOGIN_PREFIX + sessionId, verifyCode,
                securityProperties.getVerifyCode().getVerifyCodeExpiration(), TimeUnit.MINUTES);
        return verifyCode;
    }

}
